package crp.core.space.domain.models;

import com.qwlabs.lang.C2;
import com.qwlabs.tree.Tree;
import crp.core.space.domain.repositories.LocationRepository;

import java.util.Collection;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Stream;

public class LocationTree {
    private final LocationRepository locationRepository;

    public LocationTree(LocationRepository locationRepository) {
        this.locationRepository = locationRepository;
    }

    private Tree<LocationEntity> get() {
        return Tree.toTree(locationRepository.findAll().list(), LocationEntity::getId, LocationEntity::getParentId);
    }

    public Stream<LocationEntity> findOffspring(Collection<String> locationIds) {
        if (C2.isEmpty(locationIds)) {
            return Stream.empty();
        }
        Tree<LocationEntity> tree = get();
        return locationIds.stream()
                .map(locationId -> tree.findNode(location -> location.getId().equals(locationId)).orElse(null))
                .filter(Objects::nonNull)
                .flatMap(node -> node.mapDeep(Function.identity(), true).stream());
    }
}
